package com.chuangke.common.utils;

import java.util.UUID;

import com.chuangke.common.exception.ChuangkeException;

/**
 * 密码工具类
 * @author chuangke
 * @date Sep 1, 2018
 */
public class PasswordUtils {

	/**
	 * 匹配密码
	 * @param salt 盐
	 * @param rawPass 明文 
	 * @param encPass 密文
	 * @return
	 */
	public static boolean matches(String salt, String rawPass, String encPass) {
		return new PasswordEncoder(salt).matches(encPass, rawPass);
	}
	
	public static void main(String[] args) {
		String pass = "Aa123456!" ;
		encode(pass,"1") ;
	}
	
	/**
	 * 明文密码加密
	 * @param rawPass 明文
	 * @param salt
	 * @return
	 */
	public static String encode(String rawPass, String salt) {
		return encode(true,rawPass,salt) ;
	}
	
	public static String encode(boolean isValidate, String rawPass, String salt) {
		String passregx = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,20}$";
		if(isValidate && !rawPass.matches(passregx)) {
			throw new ChuangkeException("密码长度8-20位且至少包含大小写字母、数字或特殊符号中的任意三种");
		}
		return new PasswordEncoder(salt).encode(rawPass);
	}

	/**
	 * 获取加密盐
	 * @return
	 */
	public static String getSalt() {
		return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20);
	}
}
